package org.xydpeng.demo.grpc.config;

import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import net.devh.boot.grpc.server.config.GrpcServerProperties;
import net.devh.boot.grpc.server.event.GrpcServerStartedEvent;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2024/5/29
 * @description:
 */
public class GrpcNacosAutoServiceRegistration implements ApplicationContextAware, ApplicationListener<GrpcServerStartedEvent> {

    private ApplicationContext context;
    private Environment environment;

    @Autowired
    private NacosAutoServiceRegistration nacosAutoServiceRegistration;

    @Autowired
    private GrpcServerProperties grpcProperties;

    @Override
    public void onApplicationEvent(GrpcServerStartedEvent event) {
        final int port = grpcProperties.getPort();
        nacosAutoServiceRegistration.setPort(port);
        nacosAutoServiceRegistration.start();
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
        this.environment = this.context.getEnvironment();
    }
}
